package org.gnome.wsgalaxy.gnodroid;

import android.app.ActivityManager;
import android.content.Context;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.Log;

import org.json.JSONObject;

import java.io.OutputStream;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class ServiceInfomation extends ServiceBase {
    Socket m_socket = null;
    @Override
    public void
    start(byte[] firstData, Socket socket)
    {
        m_socket = socket;

        try {
            String recStr = new String(firstData, "UTF-8");
            JSONObject recJson = new JSONObject(recStr);
            String method = recJson.getString("method");
            switch (method) {
                case "GetProp":
                    __methodGetProp();
                    break;
                default:
                    throw new Exception("no such method");
            }
        } catch (Exception e) {

        }

        try {m_socket.close();} catch (Exception e) {}
    }

    void
    __methodGetProp()
    {
        JSONObject resJson = new JSONObject();
        //resJson.put("model", )
        try {
            resJson.put("model", Build.MODEL);
            resJson.put("brand", Build.BRAND);
            resJson.put("sdk", Integer.toString(Build.VERSION.SDK_INT));
            resJson.put("android_ver", "Android " + Build.VERSION.RELEASE);
            resJson.put("kernel", "linux 5.0.0");

            DisplayMetrics displayMetrics = Global.SERVICE_CONTEXT
                    .getResources()
                    .getDisplayMetrics();
            resJson.put("sc_width", displayMetrics.widthPixels);
            resJson.put("sc_height", displayMetrics.heightPixels);

            ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
            ActivityManager activityManager = (ActivityManager) Global.SERVICE_CONTEXT
                    .getSystemService(Context.ACTIVITY_SERVICE);
            activityManager.getMemoryInfo(memoryInfo);
            resJson.put("ram", memoryInfo.totalMem);

            resJson.put("rom", 123456);

            String resStr = resJson.toString();
            byte[] jsonData = resStr.getBytes("UTF-8");

            byte[] resData = new byte[jsonData.length + 4 + 1];
            ByteBuffer byteBuffer = ByteBuffer.wrap(resData);
            byteBuffer.order(ByteOrder.BIG_ENDIAN);
            byteBuffer.clear();
            byteBuffer.putInt(jsonData.length + 1);
            byteBuffer.put(jsonData);
            byteBuffer.put((byte) 0);
            OutputStream outputStream = m_socket.getOutputStream();
            outputStream.write(resData);
        }
        catch (Exception e) {
            Log.d("gnd", e.toString());
        }
    }
}
